<?php
// school/student_view.php
$page_title = 'عرض طالب';
require_once('includes/header.php');

// ============================================================
// Polyfills (PHP 5.5+)
// ============================================================
if (!function_exists('hash_equals')) {
    function hash_equals($known, $user) {
        if (!is_string($known) || !is_string($user)) return false;
        if (strlen($known) !== strlen($user)) return false;
        $r = 0;
        for ($i = 0, $n = strlen($known); $i < $n; $i++) $r |= ord($known[$i]) ^ ord($user[$i]);
        return $r === 0;
    }
}
if (!function_exists('h')) {
    function h($s) { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }
}

// ============================================================
// الوصول
// ============================================================
$is_super  = (isset($_SESSION['role']) && $_SESSION['role'] === 'super_admin');
$my_school = isset($user['school_id']) ? (int)$user['school_id'] : 0;

// ============================================================
// اكتشاف الجدول والأعمدة
// ============================================================
$T = null;
foreach (array('students','pupils','student') as $c) {
    $r = mysqli_query($conn, "SHOW TABLES LIKE '" . mysqli_real_escape_string($conn, $c) . "'");
    if ($r && mysqli_num_rows($r) > 0) { $T = $c; break; }
}
if (!$T) {
    echo '<div class="alert alert-error">❌ لا يوجد جدول students.</div>';
    require_once('includes/footer.php'); exit;
}

$cols = array(); $meta = array();
$r = mysqli_query($conn, "SHOW COLUMNS FROM `$T`");
while ($c = mysqli_fetch_assoc($r)) { $cols[] = $c['Field']; $meta[$c['Field']] = $c; }

$pick = function($names) use ($cols) {
    foreach ($names as $n) if (in_array($n, $cols, true)) return $n;
    return null;
};

$PK       = $pick(array('student_id','id'));
$NAME     = $pick(array('full_name','name','student_name','fullname'));
$SCHOOL   = $pick(array('school_id'));
$CLASS    = $pick(array('class_id','grade_id','section_id'));
$ACTIVE   = $pick(array('is_active','active','status'));
$GENDER   = $pick(array('gender','sex'));
$BIRTH    = $pick(array('birth_date','dob','date_of_birth'));
$GUARDIAN = $pick(array('guardian_name','parent_name','father_name'));
$PHONE    = $pick(array('guardian_phone','parent_phone','phone','mobile'));
$ADDRESS  = $pick(array('address','home_address'));
$NOTES    = $pick(array('notes','note','remarks'));
$EMAIL    = $pick(array('email'));

// جدول الفصول
$CLASS_TABLE = null; $CLASS_PK = null; $CLASS_NAME = null;
foreach (array('classes','grades','sections') as $ct) {
    $r = mysqli_query($conn, "SHOW TABLES LIKE '$ct'");
    if ($r && mysqli_num_rows($r) > 0) {
        $CLASS_TABLE = $ct;
        $cc = array();
        $r2 = mysqli_query($conn, "SHOW COLUMNS FROM `$ct`");
        while ($c2 = mysqli_fetch_assoc($r2)) $cc[] = $c2['Field'];
        $CLASS_PK   = in_array('class_id', $cc, true) ? 'class_id' : (in_array('id', $cc, true) ? 'id' : $cc[0]);
        $CLASS_NAME = in_array('class_name', $cc, true) ? 'class_name' : (in_array('name', $cc, true) ? 'name' : $cc[1]);
        break;
    }
}

// جدول المدارس
$schools_has = false;
if ($SCHOOL) {
    $r = mysqli_query($conn, "SHOW TABLES LIKE 'schools'");
    $schools_has = ($r && mysqli_num_rows($r) > 0);
}

// ============================================================
// قراءة الطالب
// ============================================================
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    $_SESSION['flash'] = array('type' => 'error', 'msg' => 'معرّف الطالب غير صالح.');
    header('Location: students.php'); exit;
}

$sql = "SELECT * FROM `$T` WHERE `$PK` = ? LIMIT 1";
$stmt = mysqli_prepare($conn, $sql);
if (!$stmt) {
    echo '<div class="alert alert-error">prepare: ' . h(mysqli_error($conn)) . '</div>';
    require_once('includes/footer.php'); exit;
}
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);
$s   = $res ? mysqli_fetch_assoc($res) : null;
mysqli_stmt_close($stmt);

if (!$s) {
    $_SESSION['flash'] = array('type' => 'error', 'msg' => 'الطالب غير موجود.');
    header('Location: students.php'); exit;
}

// فحص الصلاحية: school_admin لا يرى طلاب مدرسة أخرى
if (!$is_super && $SCHOOL && $my_school > 0) {
    if ((int)$s[$SCHOOL] !== $my_school) {
        echo '<div class="alert alert-error">غير مصرح بعرض هذا الطالب.</div>';
        require_once('includes/footer.php'); exit;
    }
}

// اسم الفصل
$class_name = '';
if ($CLASS && $CLASS_TABLE && isset($s[$CLASS])) {
    $stmt = mysqli_prepare($conn, "SELECT `$CLASS_NAME` FROM `$CLASS_TABLE` WHERE `$CLASS_PK` = ? LIMIT 1");
    mysqli_stmt_bind_param($stmt, 'i', $s[$CLASS]);
    mysqli_stmt_execute($stmt);
    $r2 = mysqli_stmt_get_result($stmt);
    $row = $r2 ? mysqli_fetch_row($r2) : null;
    if ($row) $class_name = $row[0];
    mysqli_stmt_close($stmt);
}

// اسم المدرسة
$school_name = '';
if ($SCHOOL && $schools_has && isset($s[$SCHOOL])) {
    $stmt = mysqli_prepare($conn, "SELECT school_name FROM schools WHERE school_id = ? LIMIT 1");
    mysqli_stmt_bind_param($stmt, 'i', $s[$SCHOOL]);
    mysqli_stmt_execute($stmt);
    $r2 = mysqli_stmt_get_result($stmt);
    $row = $r2 ? mysqli_fetch_row($r2) : null;
    if ($row) $school_name = $row[0];
    mysqli_stmt_close($stmt);
}

// ============================================================
// حذف (POST)
// ============================================================
if (empty($_SESSION['csrf_student_view'])) {
    $_SESSION['csrf_student_view'] = bin2hex(
        function_exists('random_bytes') ? random_bytes(32) : openssl_random_pseudo_bytes(32)
    );
}
$csrf = $_SESSION['csrf_student_view'];

if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['do']) && $_POST['do'] === 'delete') {
        if (!hash_equals($_SESSION['csrf_student_view'], isset($_POST['csrf']) ? $_POST['csrf'] : '')) {
            $_SESSION['flash'] = array('type' => 'error', 'msg' => 'رمز الحماية غير صالح.');
        } else {
            $stmt = mysqli_prepare($conn, "DELETE FROM `$T` WHERE `$PK` = ?");
            mysqli_stmt_bind_param($stmt, 'i', $id);
            if (mysqli_stmt_execute($stmt)) {
                if (function_exists('log_activity')) log_activity($conn, 'حذف طالب', 'id=' . $id);
                $_SESSION['flash'] = array('type' => 'success', 'msg' => 'تم حذف الطالب.');
            } else {
                $_SESSION['flash'] = array('type' => 'error', 'msg' => 'فشل الحذف: ' . mysqli_stmt_error($stmt));
            }
            mysqli_stmt_close($stmt);
        }
        header('Location: students.php'); exit;
    }
}

$flash = isset($_SESSION['flash']) ? $_SESSION['flash'] : null;
unset($_SESSION['flash']);

// تحويل ترميز بعض القيم
$gender_display = '';
if ($GENDER && !empty($s[$GENDER])) {
    $g = $s[$GENDER];
    if ($g === 'M' || $g === 'male' || $g === '1')   $gender_display = '♂ ذكر';
    elseif ($g === 'F' || $g === 'female' || $g === '0') $gender_display = '♀ أنثى';
    else $gender_display = $g;
}

$active_val = ($ACTIVE && isset($s[$ACTIVE])) ? (int)$s[$ACTIVE] : null;
?>

<?php require_once('includes/sidebar.php'); ?>

<div class="span10 main-content">

    <div class="page-header">
        <div style="display:flex;justify-content:space-between;align-items:center">
            <h2>👤 بطاقة الطالب</h2>
            <div>
                <a href="student_edit.php?id=<?php echo (int)$s[$PK]; ?>" class="btn btn-warning">✏️ تعديل</a>
                <a href="students.php" class="btn">↩ رجوع للقائمة</a>
            </div>
        </div>
    </div>

    <?php if ($flash): ?>
        <div class="alert alert-<?php echo $flash['type'] === 'error' ? 'error' : 'success'; ?>">
            <?php echo h($flash['msg']); ?>
        </div>
    <?php endif; ?>

    <div class="row-fluid">
        <div class="span8">
            <div class="table-box" style="padding:20px">
                <h3 style="margin-top:0">
                    <?php echo $NAME ? h($s[$NAME]) : ('#' . (int)$s[$PK]); ?>
                    <?php if ($active_val !== null): ?>
                        <?php if ($active_val): ?>
                            <span class="label label-success">نشط</span>
                        <?php else: ?>
                            <span class="label label-important">موقوف</span>
                        <?php endif; ?>
                    <?php endif; ?>
                </h3>

                <table class="table table-striped table-bordered">
                    <tbody>
                        <?php if ($NAME): ?>
                        <tr>
                            <th width="200">الاسم الكامل</th>
                            <td><?php echo h($s[$NAME]); ?></td>
                        </tr>
                        <?php endif; ?>

                        <?php if ($GENDER): ?>
                        <tr>
                            <th>الجنس</th>
                            <td><?php echo h($gender_display); ?></td>
                        </tr>
                        <?php endif; ?>

                        <?php if ($BIRTH): ?>
                        <tr>
                            <th>تاريخ الميلاد</th>
                            <td><?php echo h(isset($s[$BIRTH]) ? $s[$BIRTH] : ''); ?></td>
                        </tr>
                        <?php endif; ?>

                        <?php if ($CLASS && $CLASS_TABLE): ?>
                        <tr>
                            <th>الفصل</th>
                            <td><?php echo h($class_name ? $class_name : '—'); ?></td>
                        </tr>
                        <?php endif; ?>

                        <?php if ($SCHOOL && $schools_has): ?>
                        <tr>
                            <th>المدرسة</th>
                            <td><?php echo h($school_name ? $school_name : ('#' . (int)$s[$SCHOOL])); ?></td>
                        </tr>
                        <?php endif; ?>

                        <?php if ($GUARDIAN): ?>
                        <tr>
                            <th>ولي الأمر</th>
                            <td><?php echo h(isset($s[$GUARDIAN]) ? $s[$GUARDIAN] : ''); ?></td>
                        </tr>
                        <?php endif; ?>

                        <?php if ($PHONE): ?>
                        <tr>
                            <th>هاتف ولي الأمر</th>
                            <td><?php echo h(isset($s[$PHONE]) ? $s[$PHONE] : ''); ?></td>
                        </tr>
                        <?php endif; ?>

                        <?php if ($EMAIL): ?>
                        <tr>
                            <th>البريد الإلكتروني</th>
                            <td><?php echo h(isset($s[$EMAIL]) ? $s[$EMAIL] : ''); ?></td>
                        </tr>
                        <?php endif; ?>

                        <?php if ($ADDRESS): ?>
                        <tr>
                            <th>العنوان</th>
                            <td><?php echo h(isset($s[$ADDRESS]) ? $s[$ADDRESS] : ''); ?></td>
                        </tr>
                        <?php endif; ?>

                        <?php if ($NOTES): ?>
                        <tr>
                            <th>ملاحظات</th>
                            <td><?php echo nl2br(h(isset($s[$NOTES]) ? $s[$NOTES] : '')); ?></td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="span4">
            <div class="table-box" style="padding:20px">
                <h4 style="margin-top:0">إجراءات</h4>
                <p>
                    <a href="student_edit.php?id=<?php echo (int)$s[$PK]; ?>"
                       class="btn btn-warning input-block-level">✏️ تعديل بيانات الطالب</a>
                </p>
                <p>
                    <form method="post" style="margin:0"
                          onsubmit="return confirm('⚠️ حذف الطالب؟ لا يمكن التراجع.');">
                        <input type="hidden" name="csrf" value="<?php echo h($csrf); ?>">
                        <input type="hidden" name="do" value="delete">
                        <button type="submit" class="btn btn-danger input-block-level">🗑️ حذف الطالب</button>
                    </form>
                </p>
                <p>
                    <a href="students.php" class="btn input-block-level">↩ رجوع للقائمة</a>
                </p>
            </div>

            <div class="table-box" style="padding:20px;margin-top:20px">
                <h4 style="margin-top:0">معلومات تقنية</h4>
                <table style="width:100%;font-size:13px;color:#7f8c8d">
                    <tr><td>المعرّف:</td><td><?php echo (int)$s[$PK]; ?></td></tr>
                    <?php foreach (array('created_at','updated_at','date_created') as $tc):
                        if (in_array($tc, $cols, true) && !empty($s[$tc])): ?>
                        <tr>
                            <td><?php echo h($tc); ?>:</td>
                            <td><?php echo h($s[$tc]); ?></td>
                        </tr>
                    <?php endif; endforeach; ?>
                </table>
            </div>
        </div>
    </div>
</div>

<?php require_once('includes/footer.php'); ?>